using System;

namespace MsSqlSpatial.Utility
{
	public static class Command
	{
		/// <summary>
		/// Deploys assembly and associated objects to SQL Server database. 
		/// CLR Integration must be enabled before.
		/// </summary>
		/// <param name="general"></param>
		/// <param name="options"></param>
		public static void Deploy(ConnectionOptions connection, DeployPermission permission)
		{
			string assemblyFilename = typeof(MsSqlSpatial.ConvertGeometry).Assembly.Location;
			Deployment deployment = new Deployment();
			deployment.ProgressMessage += new Deployment.ProgressMessageEventHandler(deployment_ProgressMessage);
			deployment.DeployAssembly(assemblyFilename, connection.GetSqlServerConnectionString(), connection.Database, permission);
		}

		/// <summary>
		/// Removes assembly and associated objects from SQL Server database.
		/// </summary>
		/// <param name="general"></param>
		public static void Undeploy(ConnectionOptions connection)
		{
			string assemblyFilename = typeof(MsSqlSpatial.ConvertGeometry).Assembly.Location;
			Deployment deployment = new Deployment();
			deployment.ProgressMessage += new Deployment.ProgressMessageEventHandler(deployment_ProgressMessage);
			deployment.UndeployAssembly(assemblyFilename, connection.GetSqlServerConnectionString());
		}

		private static void deployment_ProgressMessage(string message)
		{
			Console.WriteLine(message + "...");
		}

		/// <summary>
		/// Imports from Shapefile datasource to SQL Server.
		/// </summary>
		/// <param name="general"></param>
		/// <param name="options"></param>
		/// <returns>Task stats.</returns>
		public static TaskStats ImportShapefile(
			ConnectionOptions connection, 
			SqlServerOptions options, 
			string shapefilePath,
			bool appendRows)
		{
			TaskStats result;

			StoredProcedures.ImportFromShapefileMain(
				shapefilePath, 
				options.Schema, 
				options.Table, 
				options.Column, 
				options.SRID, 
				options.Subtype, 
				connection.GetSqlServerConnectionString(), 
				appendRows,
				out result.RowsProcessed,
				out result.ElapsedTime);

			return result;
		}

		/// <summary>
		/// Imports from PostGIS datasource to SQL Server.
		/// </summary>
		/// <param name="general"></param>
		/// <param name="options"></param>
		/// <returns>Task stats.</returns>
		public static TaskStats ImportPostGis(
			ConnectionOptions sqlServerConnection, 
			ConnectionOptions postGisConnection, 
			SqlServerOptions sqlServerOptions,
			PostGisOptions postGisOptions,
			bool appendRows)
		{
			using (ImportPostGis import = new ImportPostGis(sqlServerConnection, postGisConnection, sqlServerOptions, postGisOptions, appendRows))
				return import.Execute();
		}

	}
}
